<?php

namespace Application\controller;

use Application\model\QuestionnaireModel;
use Cola\Controller;
class QuestionnaireController extends Controller
{
    public function getQuestionnaire() {
        $qnid = $this->get('qnid');

        $notices = $this->model('Questionnaire')->getConfig($qnid);
        $this->success($notices);
    }

    public function answer()
    {
        $answer = $this->get('answers');

        $qnid = $this->get('qnid');
        $qnname = $this->get('qnname');
        $sid = $this->get('sid');
        $actorId = $this->get('actor_id');
        $actorName = $this->get('actor_name');
        $level = $this->get('level');
        $amount = $this->get('amount');
        $answerTime = $this->get('answer_time');
        // 先记录一份日志
        logfile('QuestionnaireModel', "qnid:$qnid qnname:$qnname sid:{$sid} actorId:$actorId actorName:$actorName level:$level amount:$amount answerTime:$answerTime");

        if ($answer && $actorId && $sid && $qnid) {
            $server = $this->model('Server')->getServerBySid($sid);
            if (empty($server)) {
                logfile('QuestionnaireModel', "qnid:$qnid empty server:{$sid}");
                $this->error('服务器信息错误');
            }
            $answers = json_decode(trim($answer, '"'), true);
            $data = [];
            $i=0;
            foreach ($answers as $val) {
                $data[$i]['qnid'] = $qnid;
                $data[$i]['qnname'] = $qnname;
                $data[$i]['topic_id'] = $val['qsid'];
                $data[$i]['topic_content'] = $val['title'];
                $data[$i]['answer'] = $val['answer'];
                $data[$i]['sid'] = $sid;
                $data[$i]['actor_id'] = $actorId;
                $data[$i]['actor_name'] = $actorName;
                $data[$i]['level'] = $level;
                $data[$i]['amount'] = $amount;
                $data[$i]['answer_time'] = $answerTime;
                $data[$i]['log_dt'] = date('Y-m-d H:i:s');
                $i++;
            }
            $res = $this->model('Questionnaire')->insertData($data);
            if ($res) {
                $url = $server['ip'].':'.$server['port'];
                $param = "playerId={$actorId}&qnId={$qnid}";
                $cres = serverApi($url, "bgQuestionAnswer", $param);
                $res = json_decode($cres, true);
                if ($res['code'] != 1) {
                    logfile('QuestionnaireModel', "qnid:$qnid 通知后端失败:url: $url param:$param res:$cres");
                }
                $this->success([]);
            } else {
                logfile('QuestionnaireModel', "qnid:$qnid 插入数据错误");
                $this->error('插入数据失败');
            }
        }
        logfile('QuestionnaireModel', "qnid:$qnid 参数错误: answer:$answer, actorId:$actorId, sid:$sid");
        $this->error('参数有误');
    }
}